package com.py.korona.ui.activities.category;

import android.content.ContentValues;
import android.view.MenuItem;
import android.widget.EditText;
import com.py.korona.R;
import com.py.korona.db.model.CategoryEntity;
import com.py.korona.ui.controls.fragments.CustomFragment;

public class CategoryDetailFragmentEditor extends CustomFragment {
    private CategoryDetailFragmentListener listener;

    @Override
    public int optionsMenuResourceId() {
        return R.menu.activity_category_detail_edit;
    }

    @Override
    public int viewLayoutId() {
        return R.layout.activity_category_detail_fragment_edit;
    }

    @Override
    public void viewDidLoad() {
        EditText mTitleText = (EditText) getActivity().findViewById(R.id.DetailCategoryEditorEditCategory);
        ContentValues contentValues = listener.fragmentContentValues(this);
        String text = contentValues.getAsString(CategoryEntity.FieldNameText);
        mTitleText.setText(text);
    }

    public CategoryDetailFragmentListener getListener() {
        return listener;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        boolean result = false;
        switch (item.getItemId()) {
            case android.R.id.home: {
                listener.fragmentOnCloseAction(this);
                break;
            }
            case R.id.DetailsMenuItemEdit: {
                listener.fragmentOnEditAction(this);
                result = true;
                break;
            }
            case R.id.DetailsMenuItemCancel: {
                listener.fragmentOnCloseAction(this);
                result = true;
                break;
            }
            case R.id.DetailsMenuItemSave: {
                saveData();
                listener.fragmentOnCloseAction(this);
                result = true;
                break;
            }
            default: {
                result = super.onOptionsItemSelected(item);
                break;
            }
        }
        return result;
    }

    public void setListener(CategoryDetailFragmentListener listener) {
        this.listener = listener;
    }

    private void saveData() {
        EditText mTitleText = (EditText) getActivity().findViewById(R.id.DetailCategoryEditorEditCategory);
        ContentValues values = new ContentValues();
        values.put(CategoryEntity.FieldNameText, mTitleText.getText().toString());
        listener.fragmentOnSaveValues(this, values);
    }
}
